package com.kbtd.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kbtd.dto.Result;
import com.kbtd.dto.UserDTO;
import com.kbtd.entity.Blog;
import com.kbtd.service.IBlogService;
import com.kbtd.constant.SystemConstants;
import com.kbtd.utils.UserHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 博客控制层
 *
 * @author wp
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Resource
    private IBlogService blogService;

    //发布博客
    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {
        return blogService.saveBlog(blog);
    }

    //博客查询
    @GetMapping("/{id}")
    Result queryById(@PathVariable("id") Long id) {
        return blogService.queryById(id);
    }

    //查询热门博客
    @GetMapping("/hot")
    public Result queryHotBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        return blogService.queryHotBlog(current);
    }

    //博客点赞/取消点赞
    @PutMapping("/like/{blogId}")
    public Result likeBlog(@PathVariable Long blogId) {
        return blogService.likeBlog(blogId);
    }

    //查询博客点赞用户
    @GetMapping("/likes/{blogId}")
    public Result queryBlogLikeUser(@PathVariable Long blogId){
        return blogService.queryBlogLikeUser(blogId);
    }

    //查询我的博客
    @GetMapping("/of/me")
    public Result queryMyBlog(@RequestParam(value = "current", defaultValue = "1") Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    //查询用户博客
    @GetMapping("/of/user")
    public Result queryBlogByUserId(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam("id") Long id) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    //查询关注博主的博客
    @GetMapping("/of/follow")
    public Result queryBlogOfFollow(@RequestParam("lastId") Long lastTime, @RequestParam(value = "offset",defaultValue = "0") Integer offset) {
        return blogService.queryBlogOfFollow(lastTime,offset);
    }
}
